package com.witdata.rabbit.consumer.instance;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.witdata.rabbit.display.ExecuteDisplay;
import com.witdata.rabbit.display.InstanceDisplay;
import com.witdata.rabbit.domain.Handle;
import com.witdata.rabbit.domain.HandleStatus;
import com.witdata.rabbit.producer.InstanceProducer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

@Component
@Slf4j
@RequiredArgsConstructor
public class InstanceConsumer implements ChannelAwareMessageListener {
    private final InstanceProducer instanceProducer;
    private final InstanceDisplay instanceDisplay;
    private final ExecuteDisplay executeDisplay;

    @Override
    public void onMessage(Message message, Channel channel) {
        new Thread(() -> {
            HandleStatus handleStatus = JSON.parseObject(message.getBody(), HandleStatus.class);
            if (handleStatus.getHandle() == Handle.RegisterInstance) {
                instanceDisplay.registerInstance(handleStatus.getData());
            } else if (handleStatus.getHandle() == Handle.RunCommand) {
                executeDisplay.sendExecuteResponse(handleStatus.getData());
            }else {
                HandleStatus lock = instanceProducer.getHandleStatusMap().get(handleStatus.getId());
                if (!ObjectUtils.isEmpty(lock)) {
                    synchronized (lock) {
                        lock.setStatus(handleStatus.getStatus());
                        lock.setData(handleStatus.getData());
                        lock.notify();
                    }
                }
            }
        }).start();
    }

    @Override
    public void containerAckMode(AcknowledgeMode mode) {
        log.info("containerAckMode：{}", mode);
    }
}
